﻿$ErrorState = 2
$ErrorMessage = ""
$Trace = ""
$Value = ""
$Error.Clear()

$computer_name = "%COMPUTERNAME%"
$templatename = "%TEMPLATE%"
$vm_guid = "%VMGUID%"
$vm_name = "%VMNAME%"
$vm_desc = "%DISCRIPTION%"
$vm_owner = "%OWNER%"
$VMHostName = "%HOSTNAME%"
$vm_path = "%VMPATH%"
$vhd_path = "%VHDPATH%"
$Value = ""

           
try {
            
	Add-PSSnapin Microsoft.SystemCenter.VirtualMachineManager

    $Trace += 'Connecting to VMM Server...  \n'

	$VMMServer = Get-VMMServer -ComputerName localhost
	$vm_host = Get-VMHost -ComputerName $VMHostName
	$Template = Get-Template | where {$_.Name -eq $templatename}

    Move-VirtualHardDisk -Bus 0 -Lun 0 -IDE -Path $vhd_path -JobGroup $vm_guid

    $r = New-VM -Template $template -Name $vm_name -Description $vm_desc -Owner $vm_owner -VMHost $vm_host -UseLocalVirtualHardDisks -SkipInstallVirtualizationGuestServices -Path $vm_path -ComputerName $computer_name -JobGroup $vm_guid
            
    if ($r -eq $null) {
		$ErrorState = 1
		$Trace += 'Virtual Machine not created...  \n'
    }
    else
    {
		$ErrorState = 0
		$Trace += 'Virsto Disk successfull created...  \n'
    
    }
}
catch {
    $ErrorState = 2
    $ErrorMessage = $error[0].Exception.ToString()
}
Finally {
    $Trace += 'ErrorState:  ' + $ErrorState + ' \n'
    $Trace += 'ErrorMessage: ' + $ErrorMessage + ' \n'
   
}
            
$Results = @($ErrorState, $ErrorMessage, $Trace, $Value) 
Return $Results